package com.egoonet.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.egoonet.util.ParamUtils;
import com.egoonet.websocket.WebSocketServer;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

/**
 * 用于IMS服务器推送消息过来，然后通过sip进行分发 
 * @author wchi
 *
 */
@WebServlet("/pushmsg")
public class PushMsgServlet extends HttpServlet {
	Logger logger = LoggerFactory.getLogger(PushMsgServlet.class);
	private static final long serialVersionUID = 1L;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sendid = ParamUtils.getParameter(request, "sendid");
		String[] recvidArray = ParamUtils.getParametersBySpliter(request, "recvid", "-");
		String msgbody = ParamUtils.getParameter(request, "msgbody");
		
		Boolean isSuccess = false;
		String msg = " ";
		
		logger.debug("接收到IMS消息推送请求，sendid[{}], recvid[{}], msgbody[{}]", sendid, recvidArray, msgbody);
		List<String> recvidList = Arrays.asList(recvidArray);
		
		try {
			Preconditions.checkArgument(!Strings.isNullOrEmpty(msgbody), "null msgbdoy");
			Preconditions.checkArgument(recvidList != null && recvidList.size() > 0, "invalid recvid");

			for (String userid : recvidList) {
				isSuccess = sendMsg(sendid, userid, msgbody);
			}
		} catch (Exception ex) {
			logger.warn("消息发送失败，因"+ ex.getMessage());
			msg = ex.getMessage();
		}
		
		JSONObject obj = new JSONObject();
		obj.put("result", isSuccess);
		obj.put("msg", msg);
		logger.debug("发送消息(GET)结果[{}]", obj);
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.getWriter().write(obj.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	/**
	 * 向指定用户发送消息
	 * @param sendid
	 * @param recvid
	 * @param msgBody
	 * @return
	 */
	private boolean sendMsg(String sendid, String recvid, String msgBody){
		boolean isSuccess = false;
		try {
			isSuccess = WebSocketServer.send(sendid, recvid, msgBody);
		} catch (IOException e) {
			logger.warn("发送消息失败", e);
		}
		
		return isSuccess;
	}
	

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("收到发送消息请求，开始解析json参数");
		Boolean isSuccess = false;
		String rtmsg = " ";
		
		try{
			String jsonData = getPostData(request);
			logger.debug("json参数为[{}]", jsonData);
			Preconditions.checkArgument(!Strings.isNullOrEmpty(jsonData), "null data");
			JSONObject json = new JSONObject(jsonData);
			Preconditions.checkNotNull(json, "invalid json format");
			
			String sendid = json.getString("sendid");
			String recvid = json.getString("recvid");
			String msg = json.getString("msg");
			logger.debug("收到发送消息请求，参数解析结果：sendid[{}], recvid[{}], msg[{}]", sendid, recvid, msg);
			
			//将消息进行base64解码
			msg = new String(Base64.decodeBase64(msg));
			logger.debug("消息被base64编码过，解码结果为[{}]", msg);
			
			isSuccess = sendMsg(sendid, recvid, msg);
		}catch(Exception ex){
			rtmsg = ex.getMessage();
			logger.warn("获取jsondata时出现异常", ex);
		}
		
		JSONObject obj = new JSONObject();
		obj.put("result", isSuccess);
		obj.put("msg", rtmsg);
		logger.debug("发送消息(POST)结果[{}]", obj);
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.getWriter().write(obj.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	private String getPostData(HttpServletRequest request) throws IOException{
		StringBuilder builder = new StringBuilder();
		BufferedReader reader = request.getReader();
		try{
			String line;
			while((line = reader.readLine())!=null){
				builder.append(line).append('\n');
			}
		} finally{
			reader.close();
		}
		
		return builder.toString();
	}
}
